const fs = require('fs');
const readline = require('readline');
const nodeExcel = require('excel-export');
const path = require('path');

//根路径在 './files/下
let root = './files/';

//读取文件夹 获取文件名数组
let fileNameArray = fs.readdirSync(root);

fileNameArray.forEach(item => {
    let filePath = root + item

    fs.readFile(filePath, "utf-8",
        function (error, data) {
            if (error) {
                console.log(error);
                console.log("config文件读入出错");
            }
            //console.log(data.toString());
            let strTxt = data.toString()

            strTxt = strTxt.replace(/'/g, "\r\n"); //把 ’替换成回车

            fs.writeFile(filePath, strTxt, function (err) {
                if (err) { return err; } else {
                    //在这里运行主程序
                    getRowData()
                }
            });
        })


    function getRowData() {

        //创建逐行读取的读流
        let rowData = readline.createInterface({
            input: fs.createReadStream(filePath)
        });

        let UNB = [];
        let EQD = [];
        let DTM = [];
        let RFF = []

        //在每读一行的时候运行参数
        rowData.on('line', (line) => {
            let rowStr = line.toString()

            if (rowStr.startsWith("UNB")) {
                let index = rowStr.indexOf('+', 4)
                UNB.push(rowStr.slice(index + 1, index + 6))
            } else if (rowStr.startsWith("EQD")) {
                let index = rowStr.indexOf('+', 4)
                EQD.push(rowStr.slice(index + 1, index + 12))
            } else if (rowStr.startsWith("DTM")) {
                let index = rowStr.indexOf(':')
                DTM.push(rowStr.slice(index + 1, index + 13))
            } else if (rowStr.startsWith("RFF")) {
                let index = rowStr.indexOf(':')
                RFF.push(rowStr.slice(index + 1))
            }
        });

        //   await new Promise(resolve => setTimeout(resolve, 1000));
        //当关闭文件流的时候运行的参数
        rowData.on('close', () => {
            //i=1 是因为本身就包含了本身元素一次
            for (let i = 1; i < EQD.length; i++) {
                UNB.push(UNB[0])
            }
            console.log('数据处理完成>>>>>转换中......');

            change2Excel({ UNB, EQD, DTM, RFF })//结束后调用外部转换函数，传入参数，实现转换

        });
    /*     return { UNB, EQD, DTM, RFF }
     */}

    function change2Excel(res) {

        let conf = {}

        conf.cols = [{
            caption: 'UNB',
            type: 'string',
        },
        {
            caption: 'EQD',
            type: 'string'

        }, {
            caption: 'DTM',
            type: 'string'
        }, {
            caption: 'RFF',
            type: 'string'
        }];

        let excelRowData = []
        for (let i = 0; i < res.EQD.length; i++) {
            excelRowData.push([res.UNB[i], res.EQD[i], res.DTM[i], res.RFF[i]]);
        }

        console.log(excelRowData);
        console.log("转换完成......");

        conf.rows = excelRowData

        let result = nodeExcel.execute(conf);
        /*  var random = Math.floor(Math.random() * 10000 + 0); *///用来保证生成不同的文件名
        let output = './output/';
        let filePath = output + item + ".xlsx";  //文件名
        //开始写入excel

        fs.writeFile(filePath, result, 'binary', function (err) {
            if (err) {
                console.log(err);
            }
        });

    }
})









